import datetime
import os
import random
from datetime import timedelta
import pika
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from goods.models import Goods
from .models import Order, Cart, OrderDeta
from .ser import CartSer, OrderSer, OrderDetaSer
import uuid
import json
import redis
from django.utils.decorators import method_decorator
from django.http import JsonResponse, HttpResponse

r = redis.Redis(host='localhost', port=6379, db=0)
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from utils.ali import AliPaySDK


# class OrderView(APIView):
#     def post(self, request):
#         try:
#             # 解析 JSON 请求体
#             data = json.loads(request.body)
#             user = data.get('user')
#             # print(user, 3333333333333333)
#             goods = data.get('goods')
#             # print(goods, 4444444444444444)
#
#             # 生成唯一的订单号
#             order_id = str(uuid.uuid4())
#             # print(order_id, 555555555555555)
#
#             # 创建订单
#             order = Order.objects.create(
#                 order_id=order_id,
#                 user_id=user,
#                 goods_id=goods,
#             )
#             # print(order, 666666666)
#
#             # 连接到 RabbitMQ 服务器
#             parameters = pika.URLParameters('amqp://guest:guest@localhost/')
#             connection = pika.BlockingConnection(parameters)
#             channel = connection.channel()
#
#             # 声明交换机和队列
#             channel.exchange_declare(exchange='orders', exchange_type='direct')
#             channel.queue_declare(queue='order_queue', durable=True)
#             channel.queue_bind(exchange='orders', queue='order_queue', routing_key='order.created')
#
#             # 发送订单信息到 RabbitMQ 队列
#             message = {
#                 'order_id': order_id,
#                 'user': user,
#                 'goods': goods,
#             }
#             channel.basic_publish(exchange='orders',
#                                   routing_key='order.created',
#                                   body=json.dumps(message))
#             connection.close()
#
#             return Response({'message': 'Order created successfully'}, status=status.HTTP_201_CREATED)
#         except Exception as e:
#             return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)


# Celery 配置
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_BEAT_SCHEDULE = {
    'clean_uploaded_files': {
        'task': 'app.tasks.clean_uploaded_files',
        'schedule': timedelta(days=1),
    },
}


@method_decorator(csrf_exempt, name='dispatch')
class FileUploadView(View):
    def post(self, request):
        # 从请求中获取上传的文件块
        file = request.FILES.get('file')
        print(file, 1111111111111111)
        if not file:
            return JsonResponse({'status': 'error', 'message': 'No file provided'}, status=400)

        # 从请求的 POST 数据中获取文件名
        fileName = request.POST.get('fileName')
        print(fileName, 2222222222222222222)
        if not fileName:
            return JsonResponse({'status': 'error', 'message': 'No fileName provided'}, status=400)
        # 检查 fileName 是否包含路径分隔符
        if '/' in fileName or '\\' in fileName:
            return JsonResponse({'status': 'error', 'message': '文件名中不能包含路径分隔符'}, status=400)

        # 从请求的 POST 数据中获取当前上传的文件块序号
        currentChunk = request.POST.get('currentChunk')
        print(currentChunk, 3333333333333333333)
        if currentChunk is None:
            return JsonResponse({'status': 'error', 'message': 'No currentChunk provided'}, status=400)
        currentChunk = int(currentChunk)

        # 从请求的 POST 数据中获取文件总共的块数
        totalChunks = request.POST.get('totalChunks')
        print(totalChunks, 444444444444444444)
        if totalChunks is None:
            return JsonResponse({'status': 'error', 'message': 'No totalChunks provided'}, status=400)
        totalChunks = int(totalChunks)
        print(totalChunks, 555555555555555)

        # 构建存储上传文件块的目录路径
        upload_dir = os.path.join('media/uploads', fileName)
        print(upload_dir, 6666666666666666)
        # 检查该目录是否存在，如果不存在则创建
        if not os.path.exists(upload_dir):
            os.makedirs(upload_dir)

        # 构建当前文件块的存储路径
        chunk_path = os.path.join(upload_dir, f'chunk_{currentChunk}')
        print(chunk_path, 88888888888888)
        # 检查 chunk_path 是否正确
        print("实际的chunk_path:", chunk_path)
        # 以二进制写入模式打开文件块存储路径
        with open(chunk_path, 'wb+') as destination:
            # 遍历文件块的每个数据块并写入到目标文件中
            for chunk in file.chunks():
                destination.write(chunk)

        # 检查当前文件块是否是最后一个块
        if currentChunk == totalChunks - 1:
            print("aaaaaaaaaa")
            # 当所有文件块都上传完成后，开始合并文件
            # 以二进制写入模式打开最终合并后的文件
            with open(os.path.join('media', fileName), 'wb') as outfile:
                print("bbbbbbbbbbb")
                # 遍历所有文件块
                for i in range(totalChunks):
                    # 构建每个文件块的路径
                    chunk_path = os.path.join(upload_dir, f'chunk_{i}')
                    # 以二进制读取模式打开文件块
                    with open(chunk_path, 'rb') as infile:
                        print("ccccc")
                        # 将文件块的内容写入到最终合并后的文件中
                        outfile.write(infile.read())
                    # 删除已经合并的文件块
                    os.remove(chunk_path)
                    print("dddd")
            # 删除存储文件块的临时目录
            os.rmdir(upload_dir)
            print("eeee")
            # 从 Redis 的有序集合中移除该文件的记录，表示文件上传完成
            r.zrem('uploaded_files', fileName)

        else:
            # 如果当前文件块不是最后一个块，将文件名添加到 Redis 的有序集合中
            # 分数设置为 0，后续可根据时间更新分数用于清理操作
            r.zadd('uploaded_files', {fileName: 0})
            print("www")

        # 返回上传成功的 JSON 响应
        return JsonResponse({'status': 'success'})
    print("fff")

    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def other_methods(self, request):
        return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)

    def get(self, request):
        return self.other_methods(request)

    def put(self, request):
        return self.other_methods(request)

    def patch(self, request):
        return self.other_methods(request)

    def delete(self, request):
        return self.other_methods(request)


class CartView(APIView):
    def post(self, request):
        cart = Cart.objects.filter(goods_id=request.data.get('goods')).first()
        if cart:
            cart.num += 1
            cart.save()
            return Response({'msg': '商品已存在,数量加一'}, status=status.HTTP_201_CREATED)
        serializer = CartSer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'msg': "添加成功", 'data': serializer.data}, status=status.HTTP_201_CREATED)
        else:
            return Response({'msg': "添加失败", 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        user = request.query_params.get('user')
        total = 0
        cart = Cart.objects.filter(user=user, is_show=True)
        if cart:
            for i in cart:
                totals = i.num * int(i.goods.price)
                total += totals
        serializer = CartSer(cart, many=True)
        return Response({'msg': '获取成功', 'data': serializer.data, 'total': total}, status=status.HTTP_200_OK)

    def put(self, request):
        cart = Cart.objects.filter(id=request.query_params.get('id'), is_show=True).first()
        if cart:
            cart.num = int(request.data.get('num'))
            cart.save()
            return Response({'msg': '修改成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '修改失败'}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request):
        cart = Cart.objects.filter(id=request.query_params.get('id'), is_show=True)
        cart.delete()
        return Response({'msg': '删除成功'}, status=status.HTTP_200_OK)


def order_num():
    now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    return 'L' + now + '-' + str(random.randint(1000, 9999))


class OrderView(APIView):
    def post(self, request):
        user = request.data.get('user')

        goods = Cart.objects.filter(user=user)
        # print(goods)

        total = 0
        for i in goods:
            # print(i)
            total += i.num * int(i.goods.price)

        obj = {
            'order_id': order_num(),
            'total_price': total,
            'user': user
        }
        # print(obj)

        orderser = OrderSer(data=obj)
        # print(orderser)
        if orderser.is_valid():
            orderser.save()
            print(orderser.data)
            print(orderser.data['id'])

        for j in goods:
            obj1 = {
                'order': orderser.data['id'],
                'goods_id': j.goods.id,
                'goods_img': j.goods.image,
                'goods_name': j.goods.name,
                'goods_price': j.goods.price,
            }
            print(obj1)
            orderdeta = OrderDetaSer(data=obj1)
            if orderdeta.is_valid():
                orderdeta.save()

        goods.delete()
        return Response({'msg': '下单成功', 'code': 200, 'data': obj})


class GetLink(APIView):
    def post(self, request):
        order = request.data.get('order')
        orders = Order.objects.filter(order_id=order, status=0).first()
        if not orders:
            return Response({'msg': '订单不存在', 'code': 201})
        alipay = AliPaySDK()
        link = alipay.page_pay(order, orders.total_price, '支付')
        return Response({'link': link})


class SuccessView(APIView):
    def post(self, request):
        data = request.query_params.dict()
        ali = AliPaySDK()
        success = ali.check_sign(data)

        if success:
            order = Order.objects.filter(order_id=data['out_trade_no']).first()
            order.status = 1
            # order.pay_time = data['timestamp']
            # order.pay_num = data['trade_no']
            order.pay_type = 0
            order.save()
            shoes = OrderDeta.objects.filter(order=order.id)
            serdeta = OrderDetaSer(shoes, many=True)
            return Response({'msg': '支付成功', 'code': 200, 'data': serdeta.data})
        return Response({'msg': '支付失败', 'code': 201})


class OrderDetaView(APIView):
    def get(self, request):
        order = request.query_params.get('order')
        orders = Order.objects.filter(order_id=order).first()
        if orders:
            goods = OrderDeta.objects.filter(order=orders.id)
            serdeta = OrderDetaSer(goods, many=True)
            return Response({'msg': '获取成功', 'code': 200, 'data': serdeta.data})
        return Response({'msg': '获取失败', 'code': 201})


from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import random


class TestWebsocket(APIView):
    def get(self, request):
        # 获取信息
        # 查询数据库对比

        # update = AllDataConsumersUpdate()
        # update.all_active_visit_data()
        channel_layer = get_channel_layer()
        send_data = {"error": "1号大鹏温度太高", 'namelist': ['1001', '1002'],
                     'valuelist': [random.randint(10, 100), random.randint(100, 200)]}
        # send_data = {"name":rand.randint(1,100)}
        async_to_sync(channel_layer.group_send)(
            '1',  # 房间组名
            {
                'type': 'send_to_chrome',  # 消费者中处理的函数
                'data': send_data
            }
        )
        return JsonResponse({"code": 200, "msg": "更新数据成功"})

